﻿<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.magical.entity.Files" %>
<%@ page import="com.magical.entity.User" %>
<%@include file="tab.jsp" %>

<div>
		<div class="navbar-header"
			style="margin-left: 10px; margin-top: 10px;">
<!-- 			<img id="ImgSrc" src="" height="10" width="10">
	 			<a class="btn btn-default glyphicon glyphicon-cloud-upload" href="#"
				style="font-size: 15px; height:40px; width: 100px;" onclick="return upload(this)">上传</a>
			 -->
			<%--<div class="dropdown" style="background: #D0EEFF;border: 1px solid #99D3F5;border-radius: 4px;padding: 4px 12px;line-height: 30px;">--%>
				<%--<a href="#" class="dropdown-toggle" id="user" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">--%>
					<%--上传文件 <span class="caret"></span></a>--%>
				<%--<ul class="dropdown-menu">--%>
					<%--<input id="file" type="file" onchange="upload(this)" style="display: none">--%>
					<%--<li><button class="file" onclick="clickFile()">上传文件</button></li>--%>
					<%--<input id="directory" type="file" onchange="uploads(this)" webkitdirectory style="display: none">--%>
					<%--<li><button class="file" onclick="clickDirectory()">上传文件夹</button></li>--%>
				<%--</ul></div>--%>
			<jsp:include page="upload.jsp"></jsp:include>
		</div>
		<div id="menubutton">
			<a class="btn btn-default glyphicon glyphicon-folder-open"
				role="button"
				style="margin-left: 10px; margin-top: 10px; width: 100px;" onclick="return buildfile()">&nbsp;新建文件夹</a>

			<div class="btn-group" role="group" id="ooperation"
				style="margin-left: 10px; margin-top: 10px;">
				<a class="btn btn-default" onclick="return share(this)">分享</a>
				<a class="btn btn-default" id="download" onclick="return downloadFileSelect()">下载</a>
				<a class="btn btn-default" id="delete" onclick="return deleteall()">删除</a>
				<a class="btn btn-default" id="main-rename" onclick="return rename()" >重命名</a>
				<a class="btn btn-default" onclick="return copyto()">复制到</a>
				<a class="btn btn-default" id="main-moveto" onclick="return movetoo()">移动到</a>
                <span id="usedSpace" style="POSITION: absolute;width: 200px;top:15px;">已用空间:0/0</span>
			</div>
			<div class="input-group" style="width: 200px; float: right; margin-top: 10px; margin-right: 50px;">
                <input id="search" type="text" class="form-control"aria-label="Amount (to the nearest dollar)">
				<span id="fakebtn"class="input-group-addon glyphicon glyphicon-search" ></span>
			</div>
		</div>
	</div>
	<div class="panel panel-default" style="margin-left: 10px; margin-top: 10px">
		<!-- Default panel contents -->
		<div class="panel-heading" id="pathnav">
			<a href="/files/search?folderId=<%=((User)session.getAttribute("loginUser")).getId()%>">我的资源</a>
			<%
				Files file=(Files)request.getAttribute("file");
				String ids=(String)request.getAttribute("ids");

				if(file!=null){
					String path=file.getFullPath();
					String[] p=path.split("/");
					String[] id=ids.split("-");
					int index=0;
					for(int i=0;i<p.length;i++){
						if(p[i].equals("upload")) {
							index = i;
							break;
						}
					}
					for(int i=index+2;i<p.length;i++){

			%>

			<a href="/files/search?folderId=<%=id[i-index-1]%>&path=<%=ids%>"> /  <%=p[i]%>
			</a>
			<%
					}
				}
			%>
			<span id="navPath">

			</span>
		</div>

		<table class="table table-hover" id="mytable">
			<thead>
				<tr>
					<th><input id="checkAll" type="checkbox" onclick="swapCheck()" value="+data[i].id+" aria-label="..."></th>
					<th colspan="4" width="60%">文件名</th>
					<th>大小</th>
					<th>修改时间</th>
				</tr>
			</thead>
            <%List<Files> subfiles=(List<Files>)request.getAttribute("subfiles");%>
			<tbody id="list" >
            <%if(subfiles!=null&&subfiles.size()!=0){
                for(Files files:subfiles){
            %>
				<tr>
					<%if(files.getFiletypeId()==5){%>
					<td style="display: none"><input name="isDirectary" type="text" value="5" style="display: none"></td>
					<%}else{%>
					<td style="display: none"><input name="isDirectary" type="text" value="-1" style="display: none"></td>
					<%}%>
                    <td><input name="isSelect" onclick="checkSelected()" value="<%=files.getFileId()%>" type="checkbox" aria-label="..."></td>
                    <td colspan="4" width="60%">
                        <%if(files.getFiletypeId()==5){ %>
                        <a href="/files/search?folderId=<%=files.getFileId()%>&path=<%=ids%>">
							<img src="../img/yyc-images/filetype/icon.png" width="4%">
                        <%}%>
							<%if(files.getFiletypeId()==1){ %>
							<a target="_blank" href="/videopreview.jsp?path=<%=files.getPath()%>">
								<img src="../img/yyc-images/filetype/mp4.png" width="4%">
							<%}%>
							<%if(files.getFiletypeId()==2){
							    int userId=((User)session.getAttribute("loginUser")).getId();%>
								<a target="_blank" href="http://officeweb365.com/o/?i=15912&furl=http://magicalcloud.peihuan.net/upload/<%=userId%><%=files.getPath()%>" >
							<img src="../img/yyc-images/filetype/text.png" width="4%">
							<%}%>
							<%if(files.getFiletypeId()==3){ %>
							<img src="../img/yyc-images/filetype/mp3.png" width="4%">
							<%}%>
							<%if(files.getFiletypeId()==4){
							    int userId=((User)session.getAttribute("loginUser")).getId();%>
                                    <a target="_blank" href="http://magicalcloud.peihuan.net/upload/<%=userId%><%=files.getPath()%>" >
							<img src="../img/yyc-images/filetype/png.png" width="4%">
							<%}%>
							<%if(files.getFiletypeId()==6){
									int userId=((User)session.getAttribute("loginUser")).getId();%>
								<a target="_blank" href="http://officeweb365.com/o/?i=15912&furl=http://magicalcloud.peihuan.net/upload/<%=userId%><%=files.getPath()%>" >
							<img src="../img/yyc-images/filetype/other.png" width="4%">
							<%}%>
                         <%=files.getFileName()%>
                         <%if(files.getFiletypeId()==5||files.getFiletypeId()==1||files.getFiletypeId()==2||files.getFiletypeId()==6){%>
                         </a>
                         <%}%>
                    </td>
                    <td><% if(files.getFiletypeId()==5){%>
                    --<%}else%><%=files.getFileFullSize()%>
                    </td>
                    <td><%=files.getStringTime()%></td>
                </tr>
            <%
                }
               }
            %>
			</tbody>
		</table>
	</div>
<input type="hidden" id="toId"  value="xxx" />
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="/js/public-method.js"></script>
<script>
    $(document).ready(function read(e) {
        if(getQueryString("folderId")==null||getQueryString("folderId")=="")
            window.location.href="/files/search?folderId=<%=((User)session.getAttribute("loginUser")).getId()%>"
        showUsedSpace();
    });
    function showUsedSpace() {
        $.ajax({
            url: "../user/showUsedSpace",
            type: "Get",
            dataType: 'json',
            data: {},
            success: function (data) {
                document.getElementById("usedSpace").innerText="已用空间"+data.usedSpace+"/"+data.maxSpace;
            },
            error:function (data) {
                alert("failed")
            }
        });
    }
    function checkSelected() {
        var obj = document.getElementsByName('isSelect');
        var count=0;
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                count++;
            }
        }
        var button = document.getElementById("main-rename");
        if(count>1){
            button.setAttribute("disabled",true);
            button.removeAttribute("onclick");
		}
		else{
            button.removeAttribute("disabled");
            button.setAttribute("onclick","rename()");
		}
	}
    var isCheckAll = false;
    function swapCheck() {
        if (isCheckAll) {
            $("input[type='checkbox']").each(function() {
                this.checked = false;
            });
            isCheckAll = false;
        } else {
            $("input[type='checkbox']").each(function() {
                this.checked = true;
            });
            isCheckAll = true;
        }
        checkSelected();
    }
    //模糊查询
    $(function () {
        $('#fakebtn').click(function searchFile() {


            $.ajax({
                url: "../files/vagueSearchFile",
                type: "POST",
                dataType: 'json',
                data: {"value": search.value},
                success: function (data) {
                    <!-- 处理后端返回的数据 -->
                    var str = "";
                    var tbody = window.document.getElementById("list");
                    tbody.innerHTML = "";
                    for (i in data) {
                        str += "<tr>" ;
                        if (data[i].filetypeId==5){
                            str +="<td style=\"display: none\"><input name=\"isDirectary\" type=\"text\" value=\"5\" style=\"display: none\"></td>";

                        } else {
                            str +="<td style=\"display: none\"><input name=\"isDirectary\" type=\"text\" value=\"-1\" style=\"display: none\"></td>";
                        }
                        str+= "<td><input name=\"isSelect\" value=\"" + data[i].fileId + "\" type='checkbox'> </td>" +
                            "<td colspan=\"4\" width=\"60%\">" ;
                        switch(data[i].filetypeId){
                            case 1:str +=  "<img src=\"../img/yyc-images/filetype/mp4.png\" width=\"4%\">"+ data[i].fileName + "</td>";break;
                            case 2:str +=  "<img src=\"../img/yyc-images/filetype/text.png\" width=\"4%\">"+ data[i].fileName + "</td>";break;
                            case 3:str += "<img src=\"../img/yyc-images/filetype/mp3.png\" width=\"4%\">"+ data[i].fileName + "</td>";break;
                            case 4:str += "<img src=\"../img/yyc-images/filetype/png.png\" width=\"4%\">"+ data[i].fileName + "</td>";break;
                            case 5:str += "<img src=\"../img/yyc-images/filetype/icon.png\" width=\"4%\">"+"<a href=\"/files/search?folderId="+data[i].fileId+"\">"+ data[i].fileName +"</a>"+ "</td>";break;
                            case 6:str += "<img src=\"../img/yyc-images/filetype/other.png\" width=\"4%\">"+ data[i].fileName + "</td>";break;
                        }
                        str +="<td>" + data[i].fileFullSize + "</td>";
                        var time = new Date(data[i].uploadTime);
                        var date = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes();
                        str += "<td>" + date + "</td></tr>";
                    }
                    tbody.innerHTML += str;
                },
                error: function (data) {
                    alert("查找失败");
                }
            });
        });
    });

    //回车触发事件
    $("body").keydown(function () {
        if (event.keyCode == "13") {//keyCode=13是回车键
            $('#fakebtn').click();
        }
    });

    //下载文件
    function downloadFileSelect(){
        var direct=document.getElementsByName("isDirectary");
        var obj = document.getElementsByName('isSelect');
        var ids = "";
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                if(direct[i].value=="5"){
                    alert("文件夹下载请安装客户端")
                    return;
                }
                ids += obj[i].value + ","; //如果选中，将value添加到变量s中
            }
        }
        if (ids == '') {
            alert("请先选择要下载的文件");
        }
        else {
            window.location.href="../files/downloadFile?ids=" +ids
        }
    }
</script>
<script>
	/**复制文件及文件夹*/
	function copyto(){
        var canmove = "yes";
        var check = new Array();
        var targetdirectorypath = "";

        var id_array=new Array();
        $('input[name="isSelect"]:checked').each(function(){
            id_array.push($(this).val());//向数组中添加元素
        });
        var idstr=id_array.join(',');//将数组元素连接起来以构建一个字符串

        if(idstr.length<3){
            alert("请选择需要复制的文件");
        }else{
            //设置隐藏域的值
            document.getElementById("toId").value=idstr;
            top.layer.open({
                type: 2,			//0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                tilte: '复制到',
                area: ['800px', '500px'],
                shade: 0.6,			//遮罩透明度，默认：0.3
                shadeclose: false,	//控制点击弹层外区域关闭，默认：false
                fixed: false, 		//鼠标滚动时，层是否固定在可视区域，默认：true
                maxmin: false,		//是否允许全屏最小化，默认：false
                resize: false,		//是否允许拉伸，默认：true
                anim: 0,				//0-6的动画形式，-1不开启，默认0
                scrollbar: true,		//是否允许浏览器出现滚动条，默认：true
                move: false,			//触发拖动的元素，默认是触发标题区域拖拽
                closeBtn: 0,			//提供了两种风格的关闭按钮，可通过配置1和2来展示,如果不显示，则closeBtn: 0，默认：1
                content: 'relocation.jsp?ids='+idstr,
                btn: ['确定', '取消'],
                yes: function(index,layero){
                    /*想移动到这个位置*/
                    var toId=document.getElementById("toId").value;
                    $.ajax({
                        url:"../files/copyFiles",
                        type:"post",
                        data:{
                            "files":idstr,
                            "copyto":toId
                        },
                        success:function (data) {
                            alert("复制文件成功");
                            window.location.reload();
                },
                        error:function (data) {
                            alert("复制文件异常")
                        }

                    });
                    layer.close(index);
                },
                btn2: function(index,layero){
                    layer.close(index);}
            });
        }
        return false;
	}
    /** 移动文件及文件夹 */
    function movetoo(){
        var canmove = "yes";
        var check = new Array();
        var targetdirectorypath = "";
        var id_array=new Array();
        $('input[name="isSelect"]:checked').each(function(){
            id_array.push($(this).val());//向数组中添加元素
        });
        var idstr=id_array.join(',');//将数组元素连接起来以构建一个字符串
        if(idstr.length<3){
            alert("请选择需要移动的文件");
        }else{
            //设置隐藏域的值
            document.getElementById("toId").value=idstr;
            top.layer.open({
                type: 2,			//0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                tilte: '移动到',
                area: ['800px', '500px'],
                shade: 0.6,			//遮罩透明度，默认：0.3
                shadeclose: false,	//控制点击弹层外区域关闭，默认：false
                fixed: false, 		//鼠标滚动时，层是否固定在可视区域，默认：true
                maxmin: false,		//是否允许全屏最小化，默认：false
                resize: false,		//是否允许拉伸，默认：true
                anim: 0,				//0-6的动画形式，-1不开启，默认0
                scrollbar: true,		//是否允许浏览器出现滚动条，默认：true
                move: false,			//触发拖动的元素，默认是触发标题区域拖拽
                closeBtn: 0,			//提供了两种风格的关闭按钮，可通过配置1和2来展示,如果不显示，则closeBtn: 0，默认：1
                content: 'relocation.jsp?ids='+idstr,
                btn: ['确定', '取消'],
                yes: function(index,layero){
                    /*想移动到这个位置*/
                    var toId=document.getElementById("toId").value;
					$.ajax({
						url:"../files/moveFiles",
						type:"post",
						data:{
						    "files":idstr,
							"moveto":toId
						},
						success:function (data) {
                            layer.msg('文件移动成功', {icon: 1});
                            window.location.reload();
                        },
						error:function (data) {
							alert("移动文件异常")
                        }

					});
                    layer.close(index);
                },
                btn2: function(index,layero){
                    layer.close(index);}
            });
        }
        return false;
    }

</script>